#!/bin/bash

K=3
M=1

MINIO_SERVER_NAME="minio"
PROJECT_PATH="$HOME/czyhome/minio_config"
USER_NAME="mcloud"
client_ip="10.10.9.5"
server_ips=("10.10.9.6" "10.10.9.7" "10.10.9.8")

function start_local_server() {
    for ((i=0; i<K; i++))
    do
        nohup go run main.go -i $i -r server -p "909"$i -m=false > nohup${i}.log 2>&1 &
        echo "start server $i"
    done
}

function stop_local_server() {
    local servers=$(ps -aux | grep $USER | grep ' -r server -p 90' | grep -v grep | awk '{print $2}')
    for id in $servers
    do
        sudo kill $id
    done
}

function run_local_client() {
    if [[ $1 == "with" ]] ; then
        go run main.go -i $K -r client
    else
        go run main.go -i $K -r client -m=false
    fi
}

function start_remote_server() {
    git pull
    cd $PROJECT_PATH
    ./start_minio_server.sh
    for ((i=0; i<${#server_ips[@]}; i++))
    do
        local node=${server_ips[$i]}
        ## 改成git pull
        # scp -r $PROJECT_PATH $USER_NAME@$node:$HOME/czyhome/
        ssh $node "
            source /etc/profile
            if [ ! -d $PROJECT_PATH ]; then
                git clone https://gitee.com/czy233/minio_config.git
            fi
            cd $PROJECT_PATH
            git pull
            ./start_minio_server.sh
            cd ./sdk
            if [[ $1 == "with" ]] ; then
                nohup go run main.go -i $i -r server -p '909'$i -m=true > nohup${i}.log 2>&1 &
            else
                nohup go run main.go -i $i -r server -p '909'$i -m=false > nohup${i}.log 2>&1 &
            fi
        " &
    done
    wait
    echo "started server"
}

function stop_remote_server() {
    for ((i=0; i<${#server_ips[@]}; i++))
    do
        local node=${server_ips[$i]}
        ## 改成git pull
        # scp -r $PROJECT_PATH $USER_NAME@$node:$HOME/czyhome/
        ssh $node "
            servers=\$(ps -aux | grep $USER | grep ' -r server -p 90' | grep -v grep | awk '{print \$2}')
            for id in \$servers
            do
                sudo kill \$id
            done
            rm $PROJECT_PATH/sdk/log.file
        " &
    done
    wait
    echo "stop server"
}

function print_help() {
    echo "Usage: $0 command"
    echo "  command: run with/without"
    echo "           stop"
    echo "           client with/without"
}

## Parse mode
if [[ $# -lt 1 ]] ; then
    print_help
    exit 0
else
    MODE=$1
    shift
fi

if [ "$MODE" == "run" ]; then
    start_remote_server $1
elif [ "$MODE" == "stop" ]; then
    stop_remote_server
elif [ "$MODE" == "client" ]; then
    run_local_client $1
else
    print_help
fi